<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>报修管理</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="../lib/layui-v2.6.3/css/layui.css" media="all">
    <link rel="stylesheet" href="../css/public.css" media="all">
    <script src="../lib/layui-v2.6.3/layui.js" charset="utf-8"></script>

    <style>
        /* 原样式保留 */
        #status { width: 100px; }
        .layui-form-item .layui-inline { margin-right: 10px; }
        .layui-form-item .layui-input-inline { width: 150px; }

        /* 新增：让弹层内容垂直水平居中 */
        .layui-layer-page .layui-layer-content {
            display: flex;
            justify-content: center;
            align-items: flex-start;
            padding: 20px 0;
        }

        /* 限制弹层内部表单最大宽度，避免拉伸 */
        #editRepair {
            width: 100%;
            max-width: 400px;
            margin: 0 auto;
        }

        /* 让表单项居中（可选） */
        .limited-form .layui-form-item {
            justify-content: center;
        }
    </style>
</head>
<body>
<div class="layuimini-container">
    <div class="layuimini-main">
        <!-- 搜索区域 -->
        <fieldset class="table-search-fieldset">
            <legend>搜索信息</legend>
            <div style="margin: 10px;">
                <form class="layui-form layui-form-pane" action="">
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label">居民姓名</label>
                            <div class="layui-input-inline">
                                <input type="text" name="name" autocomplete="off" class="layui-input">
                            </div>
                        </div>

                        <div class="layui-inline">
                            <button type="submit" class="layui-btn layui-btn-primary" lay-submit lay-filter="data-search-btn">
                                <i class="layui-icon"></i> 搜 索
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </fieldset>

        <!-- 工具栏模板 -->
        <script type="text/html" id="toolbarDemo">
            <div class="layui-btn-container">
<!--                <button class="layui-btn layui-btn-normal layui-btn-sm data-add-btn" lay-event="add"> 添加 </button>-->
                <button class="layui-btn layui-btn-sm layui-btn-danger data-delete-btn" lay-event="delete"> 批量删除 </button>
            </div>
        </script>

        <!-- 数据表格 -->
        <table class="layui-hide" id="currentTableId" lay-filter="currentTableFilter"></table>

        <!-- 行内操作模板 -->
        <script type="text/html" id="currentTableBar">
            <a class="layui-btn layui-btn-normal layui-btn-xs data-count-edit" lay-event="edit">处理</a>
            <a class="layui-btn layui-btn-xs layui-btn-danger data-count-delete" lay-event="delete">删除</a>
        </script>

        <!-- 编辑 弹窗 -->
        <div id="editRepair" style="display: none;">
            <div class="layui-form layuimini-form limited-form" lay-filter="editRepairForm">
                <div class="layui-form-item" id="requestIdDiv" style="display: none;">
                    <label class="layui-form-label">报修编号</label>
                    <div class="layui-input-inline">
                        <input type="text" name="requestId" readonly class="layui-input layui-disabled">
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label required">居民姓名</label>
                    <div class="layui-input-inline">
                        <input type="text" name="name" lay-verify="required" placeholder="请输入居民姓名" class="layui-input">
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label required">报修描述</label>
                    <div class="layui-input-inline">
                        <textarea name="description" lay-verify="required" placeholder="请输入报修内容" class="layui-textarea"></textarea>
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label ">维修人员</label>
                    <div class="layui-input-inline">
                        <div class="layui-input-inline">
                            <select name="id" id="repairMan">
                                <option value="0">请选择维修人员</option>
                            </select>
                        </div>
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label ">完成时间</label>
                    <div class="layui-input-inline">
                        <input type="text" name="completedAt"  placeholder="请选择完成时间"
                               class="layui-input" onclick="layui.laydate.render({elem: this})">
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label required">状态</label>
                    <div class="layui-input-inline">
                        <select name="status" id="status2">
                            <option value="">请选择状态</option>
                        </select>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label required">处理费用</label>
                    <div class="layui-input-inline">
                        <input type="text" name="cost" placeholder="请输入处理费用" class="layui-input"></input>
                    </div>
                </div>

                <div class="layui-form-item">
                    <div class="layui-input-block">
                        <button class="layui-btn layui-btn-normal" lay-submit lay-filter="saveRepairBtn">确认保存</button>
                    </div>
                </div>
            </div>
        </div>

        <!-- 状态标签模板 -->
        <script type="text/html" id="statusTpl">
            {{# if(d.status == 0){ }}
            <span class="layui-badge layui-bg-green">待处理</span>
            {{# } else if(d.status == 1){ }}
            <span class="layui-badge layui-bg-blue">已处理</span>
            {{# } }}
        </script>

        <!-- JS 逻辑 -->
        <script>
            layui.use(['form', 'table', 'layer'], function () {
                var $ = layui.jquery;
                var form = layui.form;
                var table = layui.table;
                var layer = layui.layer;

                // 全局设置ajax请求头
                $.ajaxSetup({
                    beforeSend: function(xhr) {
                        const data = JSON.parse(localStorage.getItem('user'));
                        //输出token
                        console.log(data.token);
                        if (data.token) {
                            xhr.setRequestHeader('Authorization', 'Bearer ' + data.token);
                        }
                    }
                });

                // 加载下拉框
                function loadSelectOptions(url, selectId) {
                    $.getJSON(url, function (res) {
                        if (res.code === 0 && res.data) {
                            var options = '';
                            res.data.forEach(function (item) {
                                options += `<option value="${item.id}">${item.value}</option>`;
                            });
                            $(selectId).append(options);
                            form.render('select');
                        }
                    });
                }
                // loadSelectOptions('/apply/priorities', '#priorities')
                loadSelectOptions('/repairMan/getRepairManOptions', '#repairMan');
                // loadSelectOptions('/apply/priorities', '#priorities');
                loadSelectOptions('/apply/priorities', '#priorities2');
                // loadSelectOptions('/apply/status', '#status');
                loadSelectOptions('/apply/status', '#status2');

                // 渲染表格
                table.render({
                    elem: '#currentTableId',
                    url: '/apply/all',
                    toolbar: '#toolbarDemo',
                    defaultToolbar: ['filter', 'exports', 'print'],
                    parseData: function (res) {
                        return {
                            "code": res.code,
                            "msg": res.message,
                            "count": res.count,
                            "data": res.data.list
                        };
                    },
                    cols: [[
                        {type: "checkbox", width: 50},
                        {field: 'requestId', title: '报修ID', sort: true},
                        {field: 'name', title: '居民姓名', sort: true},
                        {field: 'description', title: '报修描述'},
                        {field: 'priority', title: '优先级', sort: true, templet: function (d) {
                            return d.priority === 3 ? '<span class="layui-badge layui-bg-red">高</span>' :
                                d.priority === 2 ? '<span class="layui-badge layui-bg-orange">中</span>' :
                                    '<span class="layui-badge layui-bg-green">低</span>';
                            }},
                        {field: 'createdAt', title: '申请时间', sort: true},
                        {field: 'status', title: '状态', templet: '#statusTpl'},
                        {title: '操作', minWidth: 100, templet: '#currentTableBar', align: "center"}
                    ]],
                    limits: [10, 15, 20, 25, 50, 100],
                    limit: 15,
                    page: true,
                    skin: 'line',
                    response: {
                        statusName: 'code',
                        statusCode: 0,
                        msgName: 'message',
                        countName: 'count',
                        dataName: 'data'
                    }
                });

                // 搜索
                form.on('submit(data-search-btn)', function (data) {

                    table.reload('currentTableId', { where: data.field });
                    return false;
                });

                // 工具栏
                table.on('toolbar(currentTableFilter)', function (obj) {
                   if (obj.event === 'delete') {
                        const ids = table.checkStatus('currentTableId').data.map(i => i.requestId);
                        $.ajax({
                            url: '/apply/deleteBatch',
                            type: 'POST',
                            contentType: 'application/json',
                            data: JSON.stringify(ids),
                            success: res => {
                                layer.msg(res.code === 0 ? '删除成功' : (res.message || '删除失败'));
                                table.reload('currentTableId');
                            }
                        });
                    }
                });

                // 行内操作
                table.on('tool(currentTableFilter)', function (obj) {
                    const data = obj.data;
                    if (obj.event === 'edit') {
                        tag = 1;
                        form.val("editRepairForm", data);
                        $("#requestIdDiv").show();
                        layer.open({
                            title: '处理报修申请',
                            type: 1,
                            area: ['60%', '60%'],
                            offset: 'auto',
                            content: $('#editRepair')
                        });
                    } else if (obj.event === 'delete') {
                        layer.confirm('确定删除该记录？', function (index) {

                            const url = '/apply/delete'+'?requestId='+data.requestId;
                            $.ajax({
                                url: url,
                                type: 'POST',
                                contentType: 'application/json',
                                success: res => {
                                    layer.msg(res.message);
                                    table.reload('currentTableId');
                                    layer.closeAll();
                                }
                            });
                            obj.del(); layer.close(index);
                        });
                    }
                });

                // 保存
                form.on('submit(saveRepairBtn)', function (data) {

                    const url = '/repair/add';
                    const  field ={
                        "completedAt": data.field.completedAt,
                        "cost": data.field.cost,
                        "id":data.field.id,
                        "repairDescription": data.field.description,
                        "requestId":data.field.requestId,
                        "status": data.field.status
                    }


                    $.ajax({
                        url: url,
                        type: 'POST',
                        contentType: 'application/json',
                        data: JSON.stringify(field),
                        success: res => {
                            layer.msg(res.code === 0 ? "处理成功" : '操作失败');
                            table.reload('currentTableId');
                            layer.closeAll();
                        },
                        error: function (res) {
                            layer.msg('操作失败');
                        }
                    });
                    return false;
                });
            });
        </script>
    </div>
</div>
</body>
</html>